package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

var wg sync.WaitGroup
var stop = make(chan bool)

//func cpuInfo() {
//	defer wg.Done()
//	for {
//		select {
//		case <-stop:
//			fmt.Println("退出cpu监控")
//			return
//		default:
//			time.Sleep(time.Second * 2)
//			fmt.Println("cpu信息读取完成")
//		}
//	}
//}

func cpuInfo(ctx context.Context) {
	defer wg.Done()
	//父的context取消那么这个父context生成的子context也会被取消
	//ctx2, _ := context.WithCancel(ctx)
	//go memoryInfo(ctx2)
	for {
		select {
		case <-ctx.Done():
			fmt.Println("监控推出")
			return
		default:
			time.Sleep(time.Second)
			fmt.Println("获取cpu信息成功")
		}

	}
}
func memoryInfo(ctx context.Context) {
	defer wg.Done()
	for {
		select {
		case <-ctx.Done():
			fmt.Println("监控内存退出")
			return
		default:
			time.Sleep(time.Second)
			fmt.Println("获取内存信息成功")
		}

	}
}
func main() {
	//现在启动一个goroutine去监控某台服务器的cpu使用情况
	wg.Add(1)
	//ctx, cancel := context.WithCancel(context.Background())
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	go cpuInfo(ctx)
	time.Sleep(time.Second * 1)
	cancel()
	//time.Sleep(time.Second * 6)
	//cancel()
	//stop <- true
	wg.Wait()
	fmt.Println("信息监控完成")
}
